﻿(function ($) {
    $.extend({
        ColorLife: {
            returnOpenerId: '', // insert file to opener element Id
            returnFullUrl: false, // true: return full url same as: http://your-domain.com/upload/file.jpg            
            tinymce:'',            
            serviceUrl: 'http://localhost/content/editors/filemanager/FileService.asmx/',
            iconsPath: '/content/editors/filemanager/icons/',
            imageThumbnail: '/ThumbnailHandler.axd?img=',

            txtPath: '#txtPath',
            rootFolder: '/Uploads',
            currentFolder: '',
            currentFile: '',
            prevFolder: '',            
            Copy: null,
            Cut: null,
            containerId: '#_fileContainer',
            loadingId: '#_loading',
            loaderID: '#loader',            
            itemInfoId: '#_itemInfo',
            itemPreview: '#_preview',
            itemClass: 'xfm-item',
            itemSelectedClass: 'xfm-item-selected',
            itemSelectedNoFocusClass: 'xfm-item-selected-nofocus',
            itemHoverClass: 'xfm-item-over',
            itemNameClass: 'xfm-item-name',
            itemCutClass: 'xfm-item-cut',
            imagePattern:/\.(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG|doc|pdf)$/,
            rememberLastPath: true, // save last path
            pageIndex: 1, // current page index          
            filter: '0', //* all files and folders , *.* only files
            sortOrder: '', // sort "Name DESC","Size","Date", LastWriteDate asc/desc
            searchTxt: '',
            multiSelect: false,
            clipboardData: '',
            clipboardType: 'cut',  // cut || copy          
            items: {},            
            viewType: 'icons', //list,detail,icons
            messages: {
                mustSelectItem: 'Bạn phải chọn file hoặc thư mục nào đó',
                deleteItemsConfirm: 'Are you sure you want to delete the selected "{0}" files?',
                folderEmpty: 'This folder is empty.',
                overwriteExists: 'Bạn có muốn ghi đè file / thư mục đã có?',
                folderInfo: '{0} folders, {1} files',
                //fileCount:'Showing page {0} through {1} out of {2} in this folder'                
                searchFile: 'Search files'
            },
            Cookie: {
                prefix: 'CLFileManager_',
                cookieDays: 30, // use late
                add: function (name, value, days) {
                    if (days) {
                        var date = new Date();
                        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                        var expires = "; expires=" + date.toGMTString();
                    }
                    else var expires = "";
                    document.cookie = this.prefix + name + "=" + value + expires + "; path=/";
                },
                get: function (name) {
                    var nameEQ = this.prefix + name + "=";
                    var ca = document.cookie.split(';');
                    for (var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                        if (c.indexOf(nameEQ) == 0) {
                            return c.substring(nameEQ.length, c.length);
                        }
                    }
                    return "";
                },
                remove: function (name) {
                    this.Add(this.prefix + name, "", -1);
                }
            },
            String: {
                trim: function () {
                    return this.replace(/^\s+|\s+$/g, '');
                },

                //if( $.StringEx.isNullOrEmpty('') ) alert('Empty string');
                isNullOrEmpty: function (value) {
                    if (value) {
                        if (typeof (value) == 'string') {
                            if (value.length > 0)
                                return false;
                        }
                        if (value != null)
                            return false;
                    }
                    return true;

                },

                replace: function (source, oldVal, newVal) {
                    var result = source;
                    //result = result.replace(oldVal, newVal);
                    result = result.replace(new RegExp(oldVal, 'ig'), newVal);
                    //result = result.replace(new RegExp('\\' + oldVal + '\\', 'g'), newVal);

                    return result;
                },

                //alert( $.StringEx.format("Hello {0}.","Nasa8x") );
                format: function (format, args) {
                    var result = format;
                    for (var i = 1; i < arguments.length; i++) {
                        result = result.replace(new RegExp('\\{' + (i - 1) + '\\}', 'g'), arguments[i]);
                    }
                    return result;
                },
                startsWith: function (prefix, ignoreCase) {
                    if (!prefix) return false;
                    if (prefix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
                        }
                    }
                    return (this.substr(0, prefix.length) === prefix);
                },
                endsWith: function (suffix, ignoreCase) {
                    if (!suffix) return false;
                    if (suffix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
                        }
                    }
                    return (this.substr(this.length - suffix.length) === suffix);
                }
            },
            // HELPER //
            _undefined: function () {
                for (var i = 0; i < arguments.length; i++)
                    if (typeof arguments[i] != 'undefined') return false;
                return true;
            },
            _viewport: function () {
                var d = document.documentElement, b = document.body, w = window;
                return jQuery.extend(
                    // jQuery.browser.msie ?
                    /msie/.test(navigator.userAgent.toLowerCase()) ?
                        { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop} :
                        { left: w.pageXOffset, top: w.pageYOffset },
                    !this._undefined(w.innerWidth) ?
                        { width: w.innerWidth, height: w.innerHeight} :
                        (!this._undefined(d) && !this._undefined(d.clientWidth) && d.clientWidth != 0 ?
                            { width: d.clientWidth, height: d.clientHeight} :
                            { width: b.clientWidth, height: b.clientHeight }));
            },
            _overlay: function (status, callback) {
                switch (status) {
                    case 'show':
                        $("body").append('<div id="_overlay"></div>');
                        $("#_overlay").css({
                            position: 'absolute',
                            zIndex: 9000,
                            top: '0px',
                            left: '0px',
                            width: '100%',
                            background: '#333333',
                            opacity: 0.2,
                            height: $(document).height()

                        }).fadeIn(500, function () {
                            if ($.isFunction(callback))
                                callback.apply();
                        });
                        break;
                    case 'hide':
                        $('#_overlay').fadeOut('fast', function () {
                            $("#_overlay").remove();
                            if ($.isFunction(callback))
                                callback.apply();

                        });

                        break;
                }
            },
            elementsCenterScreen: function () {
                var _v = this._viewport();
                for (var i = 0; i < arguments.length; i++) {
                    var _left = (_v.width - $('#' + arguments[i]).outerWidth()) / 2;
                    var _top = _v.top + (_v.height + $('#' + arguments[i]).outerHeight()) / 2;
                    $('#' + arguments[i]).css({ top: _top, left: _left });

                }

            },
            showLoading: function (sender, args) {
                this._overlay('show');
                var _v = this._viewport();
                var _left = (_v.width - $(this.loadingId).outerWidth()) / 2;
                var _top = _v.top + (_v.height - $(this.loadingId).outerHeight()) / 2;
                $(this.loadingId).css({ top: _top, left: _left }).show();

                //alert('Loading');

            },
            hideLoading: function (sender, args) {
                $(this.loadingId).fadeOut();
                this._overlay('hide');
            },
            getQueryString: function (key) {
                key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regex = new RegExp("[\\?&]" + key + "=([^&#]*)", 'ig');
                var qs = regex.exec(window.location.href);
                if (qs == null)
                    return '';
                else
                    return qs[1];
            },
            getParentWin: function () {
                var w = opener || parent;
                return w != window ? w : null;
            },
            isEnter: function (event) {
                return ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13));
            },

            insertFile: function () {
                var url = this.currentFile;
                var win = this.getParentWin();                
                if (this.returnOpenerId != null && this.returnOpenerId != '') {
                    win.document.getElementById(this.returnOpenerId).value = url;
                    self.close();
                }

                else if (this.tinymce) { // Plugin TinyMce 
                    if (this.tinymce == 'preview') {
                        $.ColorLife.tyinyMCE_insertFile(_item, _item);  // Xem anh truoc khi chen
                    }
                    else {
                        alert('Chen anh truc tiep, khong can xem truoc');
                        
                        tinyMCE.activeEditor.selection.setContent("HAAAAA");

                         ImageDialog.insert(_item, _item);                       
                    }
                }

                else if (navigator.appName.indexOf('Microsoft') != -1) {
                    window.returnValue = url;
                    self.close();
                }
            },
            tyinyMCE_insertFile: function (fileName, title) {
                var win = tinyMCEPopup.getWindowArg("window");
                win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = fileName;
                if (typeof (win.ImageDialog) != "undefined") {

                    if (win.ImageDialog.getImageData)
                        win.ImageDialog.getImageData();

                    if (win.ImageDialog.showPreviewImage)
                        win.ImageDialog.showPreviewImage(fileName);
                }
                tinyMCEPopup.close();
            },
            isImage: function (_fileExt) {                             
                var reg = $.ColorLife.imagePattern; // /\.(jpg|JPG|gif|doc|pdf)$/;
                return reg.test(_fileExt);
            },
            checkExtension: function (text) {
                var reg = /\.(jpg|gif|doc|pdf)$/
                return reg.test(text);
            },
            checkExt: function (filename) {//use in a form event or ina input
                var ext = /^.+\.([^.]+)$/.exec(filename);
                return ext == null ? "" : ext[1];
            },
            saveFileToServer: function (fileUrl) {
                if (fileUrl.length > 0 && $.ColorLife.isImage(fileUrl)) {
                    var params = "{'folderPath':'" + $.ColorLife.currentFolder + "','fileUrl':'" + fileUrl + "'}";
                    $.ColorLife.ajaxCallback('SaveFileToServer', params, $.ColorLife.refresh);
                    alert('Save file successfull.');
                }
                else {
                    alert('Please Enter file web address.');
                }
            },
            doUpload: function () {
                if (pluginlist.indexOf("Flash") != -1) {
                    $("#file-upload-dialog").uploadify({
                        'swf': '/content/filemanager/js/uploader/uploadify.swf',
                        'uploader': '/FileUpload.axd',

                        'buttonText': 'UPLOAD FILE (S)',
                        'fileTypeExts': '*.jpg;*.gif;*.png;*.bmp',
                        'fileTypeDesc': 'Image Files',
                        'multi': true,
                        'auto': true,
                        'formData': {
                            'folder': $.ColorLife.currentFolder,
                            'tocken': 'tuanitpro'
                        },
                        'onInit': function (instance) {
                            //  alert('The queue ID is ' + instance.settings.uploader + $.ColorLife.currentFolder);
                        },
                        'onQueueComplete': function (queueData) {
                            $('.alert').show();
                            $('.rseult').html(queueData.uploadsSuccessful + ' files were successfully uploaded. ' + queueData.uploadsErrored + ' files ware errored.');
                            $.ColorLife.refresh();
                        }
                    });
                }
                else {
                    // alert('Please install flash plugin to upload file.');
                    $.ColorLife.ajaxUpload($("#file-upload-dialog"));
                }
            },
            ajaxUpload: function (action) {

                new AjaxUpload(action, {
                    action: '/FileUpload.axd',
                    name: 'myFile',
                    data: { 'folder': $.ColorLife.currentFolder },
                    autoSubmit: true,
                    onSubmit: function (file, extension) {
                        if (!(extension && /^(jpg|png|jpeg|gif|bmp|JPG|PNG|JPEG|BMP|GIF)$/.test(extension))) {

                            alert('Only JPG, PNG or GIF files are allowed');

                            return false;
                        }

                    },
                    onComplete: function (file, response) {                       
                        var resp = response;
                        resp = jQuery(resp).html();
                        $('.alert').show();
                        $('.rseult').html(resp);
                        $.ColorLife.refresh();
                        return true;
                    }
                });
            },
            ajaxCallback: function (cmd, params, callback) {
                this.showLoading();
                $(this.itemInfoId).html('');
                $(this.itemPreview).html('');
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: (params),
                    url: this.serviceUrl + cmd,
                    beforeSend: function () {
                        $(this.loaderID).show();
                    },
                    success: function (response) {
                        
                        var result = (typeof response) == 'string' ? eval('(' + response + ')') : response.d;
                        if ($.isFunction(callback)) {
                            callback(result);
                        }
                        $(this.loaderID).hide();
                        $.ColorLife.hideLoading();
                    },
                    error: function (xhr, status) {
                        alert(status);
                    }
                });
            },
            selectItemInfo: function (i) {
                // clear class item no selected
                //   $('.' + $.xFM.itemSelectedClass).removeClass($.xFM.itemSelectedNoFocusClass);
                var html1 = "";
                var _item = $.ColorLife.items[i];
               
                var _icon = this.iconsPath + 'none.gif';
                if (_item.IsFolder) {
                    _icon = this.iconsPath + 'folder.gif';
                }
                else if (this.isImage(_item.Name)) {
                    _icon = this.imageThumbnail + _item.FullName;
                    html1 = "<img src=" + _item.FullName.replace(/' '/g, "%20") + " width='100%'/>";
                }
                else if (_item.IsExistsIcon) {
                    var ext = this.checkExt(_item.FullName);
                    switch (ext.toLowerCase()) {

                        case "swf":
                            html1 += '<embed type="application/x-shockwave-flash" quality="high" wmode="transparent" src="' + _item.FullName + '">';
                            _icon = this.iconsPath + _item.Extension.replace('.', '') + '.gif';
                            html = "<img src='" + _icon + "' width='48px'/>";
                            break;
                        default:
                            _icon = this.iconsPath + _item.Extension.replace('.', '') + '.gif';
                            html1 = "<img src='" + _icon + "' width='48px'/>";
                            break;
                        // bg = "ThumbnailHandler.axd?img=" + _item + "";                           
                    }
                }
                this.currentFile = _item.FullName;

                var _html = '<div class="item-info item-info-icon" style="background: url(\'' + _icon + '\') no-repeat center center;">';
                //_html += '<img class="" src="' + _icon + '" />';
                _html += '</div>';
                _html += '<div class="item-info item-info-content">';
                _html += '<div class="line-1 item-info-name">' + _item.Name + '</div>';
                if (_item.IsFolder) {
                    _html += '<div class="line-2">' + _item.SubFolderCount + ' folders, ' + _item.FileCount + ' files</div>';
                }
                else {
                    _html += '<div class="line-2"><span class="item-info-label">Size: </span>' + _item.Size + '</div>';
                }
                _html += '</div>';

                $(this.itemInfoId).html(_html);

                $(this.itemPreview).html(html1);

                $(this.txtPath).val(_item.FullName);
                // TODELETE
                $("#deleteConfirm").html(this.messages.deleteItemsConfirm.replace('{0}', _item.FullName));
                $("#quickDelete").show();
                $("#imgmodal").attr('src', _item.FullName);
            },
            getSelectedItems: function () {
                
                var _items = new Array();
                // $("input[@class='item-selected']:checked").each(function() {
                $('.' + this.itemSelectedClass).each(function () {
                    _items.push($(this).attr('rel'));
                });
                return _items;
            },
            dbSelectItem: function (_type, _item) { // dblclick
                if (_type == 'folder') {
                    this.loadFileFolder(_item);
                }
                else {
                    var win = this.getParentWin();
                    if (this.returnOpenerId != null && this.returnOpenerId != '') {
                        win.document.getElementById(this.returnOpenerId).value = _item;
                        win.document.getElementById("imgthumb").src = _item;
                        self.close();
                        parent.$.colorbox.close();
                    } else {
                        if (this.tinymce == 'preview') {
                            this.tyinyMCE_insertFile(_item, _item);  // Xem anh truoc khi chen
                        }
                        else {
                            var img = "<img src='" + _item + "'/>";
                            tinyMCE.activeEditor.selection.setContent(img);

                            tinyMCEPopup.close();
                            // ImageDialog.insert(_item, _item);               // Chen anh truc tiep, khong can xem truoc                       
                        }
                    }
                }
            },
            selectAllItems: function () {
                $('.' + this.itemClass).addClass(this.itemSelectedClass);
            },
            buildTypeIcons: function () {
                var _html = '<ul class="xfm-' + this.viewType + '">';
                var _iconPath = this.iconsPath;

                $.each($.ColorLife.items, function (i, item) {

                    if (item.IsFolder) {
                        $.ColorLife.folderInfo.subFolders += 1;
                    }
                    else {
                        $.ColorLife.folderInfo.files += 1;
                    }
                    var _icon = _iconPath + 'none.gif';
                    var _type = 'file';
                    if (item.IsFolder) {
                        _icon = _iconPath + 'folder.gif';
                        _type = 'folder';
                    }
                    else if ($.ColorLife.isImage(item.FullName)) {
                        _icon = $.ColorLife.imageThumbnail + item.FullName;
                    }
                    else if (item.IsExistsIcon) {
                        _icon = _iconPath + item.Extension.replace('.', '') + '.gif';
                    };
                    _html += '<li id="xfm-item-' + i + '" title="' + item.Name + '" class="' + $.ColorLife.itemClass + ' ' + _type + '" stt="' + i + '" type="' + _type + '" rel="' + item.FullName + '" data-toggle="context" data-target="#context-menu">';
                    _html += '<div class="xfm-item-thumb align-center" ondblclick=\"$.ColorLife.dbSelectItem(\'' + _type + '\',\'' + item.FullName + '\')\" style="background: url(\'' + _icon + '\') no-repeat center center;">';

                    _html += '</div>';
                    _html += '<div id="xfm_item_' + i + '" class="align-center ' + $.ColorLife.itemNameClass + '">' + item.Name + '</div>';
                    _html += '</li>';
                });

                _html += '</ul>';


                $(this.containerId).html(_html);

                $('.' + this.itemClass).mousedown(
                function (e) {
                    if (e.shiftKey || e.ctrlKey) {
                        $(this).toggleClass($.ColorLife.itemSelectedClass);
                        //$.ColorLife.multiSelect = true;
                    };
                    $(this).addClass($.ColorLife.itemSelectedClass);
                })
                .click(function (e) {
                    // var obj = (e.target || e.srcElement); if (obj.href || obj.type) return true;
                    if (!e.shiftKey && !e.ctrlKey) {
                        $($.ColorLife.containerId + ' li').removeClass($.ColorLife.itemSelectedClass);
                        $(this).addClass($.ColorLife.itemSelectedClass);

                    };

                    $.ColorLife.selectItemInfo($(this).attr('stt'));

                    $(this).removeClass($.ColorLife.itemSelectedNoFocusClass); //.addClass($.xFM.itemSelectedClass);

                })

                .hover(function (e) {
                    $(this).addClass($.ColorLife.itemHoverClass);
                },
                function () {
                    $(this).removeClass($.ColorLife.itemHoverClass);
                });
            },
            buildTypeList: function () {
                var _html = '<ul class="xfm-' + $.ColorLife.viewType + '">';
                var _iconPath = $.ColorLife.iconsPath;

                $.each($.ColorLife.items, function (i, item) {

                    if (item.IsFolder) {
                        $.ColorLife.folderInfo.subFolders += 1;
                    }
                    else {
                        $.ColorLife.folderInfo.files += 1;
                    }
                    var _icon = _iconPath + 'none.gif';
                    var _type = 'file';
                    if (item.IsFolder) {
                        _icon = _iconPath + 'folder.gif';
                        _type = 'folder';
                    }
                    else if ($.ColorLife.isImage(item.FullName)) {
                        _icon = $.ColorLife.imageThumbnail+ item.FullName;
                    }
                    else if (item.IsExistsIcon) {
                        _icon = _iconPath + item.Extension.replace('.', '') + '.gif';
                    };

                    _html += '<li id="xfm-item-' + i + '" title="' + item.Name + '" class="' + $.ColorLife.itemClass + ' ' + _type + ' ui-draggable ui-droppable  xfm-item-selected" stt="' + i + '" type="' + _type + '" rel="' + item.FullName + '">';
                    _html += '<div class="xfm-item-thumb align-center" onmousedown=\"$.ColorLife.dbSelectItem(\'' + _type + '\',\'' + item.FullName + '\')\" style="background: url(\'' + _icon + '\') no-repeat center center;">';

                    //_html += '<img src="' + _icon + '" />';

                    _html += '</div>';
                    _html += '<div id="xfm_item_' + i + '" class="align-center ' + $.ColorLife.itemNameClass + '">' + item.Name + '</div>';
                    _html += '</li>';
                });

                _html += '</ul>';

                $($.ColorLife.containerId).html(_html);
            },
            buildTypeDetail: function () {
                var _html = '<ul class="xfm-' + $.ColorLife.viewType + '">';
                var _iconPath = $.ColorLife.iconsPath;
                $.each($.ColorLife.items, function (i, item) {

                    if (item.IsFolder) {
                        $.ColorLife.folderInfo.subFolders += 1;
                    }
                    else {
                        $.ColorLife.folderInfo.files += 1;
                    }
                    var _icon = _iconPath + 'none.gif';
                    var _type = 'file';
                    if (item.IsFolder) {
                        _icon = _iconPath + 'folder.gif';
                        _type = 'folder';
                    }
                    else if ($.ColorLife.isImage(item.FullName)) {
                        _icon = $.ColorLife.imageThumbnail + item.FullName;
                    }
                    else if (item.IsExistsIcon) {
                        _icon = _iconPath + item.Extension.replace('.', '') + '.gif';
                    };

                    _html += '<li id="xfm-item-' + i + '" title="' + item.Name + '" class="' + $.ColorLife.itemClass + ' ' + _type + '" stt="' + i + '" type="' + _type + '" rel="' + item.FullName + '">';
                    _html += '<div class="xfm-item-thumb align-center" onmousedown=\"$.ColorLife.dbSelectItem(\'' + _type + '\',\'' + item.FullName + '\')\" style="background: url(\'' + _icon + '\') no-repeat center center;">';

                    //_html += '<img src="' + _icon + '" />';

                    _html += '</div>';
                    _html += '<div id="xfm_item_' + i + '" class="align-center ' + $.ColorLife.itemNameClass + '">' + item.Name + '</div>';
                    _html += '</li>';
                });

                _html += '</ul>';

                $($.ColorLife.containerId).html(_html);
                $('.' + this.itemClass)
                 .mousedown(function (e) {
                     if (e.shiftKey || e.ctrlKey) {
                         $(this).toggleClass($.ColorLife.itemSelectedClass);
                         //$.ColorLife.multiSelect = true;
                     };
                     $(this).addClass($.ColorLife.itemSelectedClass);
                 })
                .click(function (e) {
                    // var obj = (e.target || e.srcElement); if (obj.href || obj.type) return true;
                    if (!e.shiftKey && !e.ctrlKey) {
                        $($.ColorLife.containerId + ' li').removeClass($.ColorLife.itemSelectedClass);
                        $(this).addClass($.ColorLife.itemSelectedClass);

                    };

                    $.ColorLife.selectItemInfo($(this).attr('stt'));

                    $(this).removeClass($.ColorLife.itemSelectedNoFocusClass); //.addClass($.xFM.itemSelectedClass);
                }).hover(function (e) {
                    $(this).addClass($.ColorLife.itemHoverClass);
                },
                function () {
                    $(this).removeClass($.ColorLife.itemHoverClass);
                });
            },
            buildData: function (result) {
                if (result.length > 0) {
                    $.ColorLife.items = result;
                    if ($.ColorLife.viewType == 'icons') {
                        $.ColorLife.buildTypeIcons();
                    }
                    if ($.ColorLife.viewType == 'list') {
                        $.ColorLife.buildTypeList();
                    }
                    if ($.ColorLife.viewType == 'detail') {
                        $.ColorLife.buildTypeDetail();
                    }
                    $.ColorLife.clickToReName();
                }
                else {
                    $($.ColorLife.containerId).html('<div class="empty">' + $.ColorLife.messages.folderEmpty + '</div>');
                };
            },

            // LOAD DATA //
            loadFileFolder: function (path) {
                $(this.txtPath).val(path);                
                this.currentFolder = path;
                $("#deleteConfirm").html(this.messages.deleteItemsConfirm.replace('{0}', path));
                if (path != $.ColorLife.rootFolder) {
                    $('#_back').show();
                }
                else {
                    $('#_back').hide();
                }
                var params = "{'path':'" + path + "','searchTxt':'','sortOrder':'" + this.sortOrder + "','filter':" + $.ColorLife.filter + "}";
                $.ColorLife.ajaxCallback('LoadAllFileFolder', params, $.ColorLife.buildData);
                //$.ajax({
                //    type: "POST",
                //    contentType: "application/json; charset=utf-8",
                //    dataType: "json",
                //    data: (params),
                //    url: $.ColorLife.serviceUrl + cmd,
                //    beforeSend: function () {
                //        $($.ColorLife.loaderID).show();
                //    },
                //    success: function (response) {

                //        var result = (typeof response) == 'string' ? eval('(' + response + ')') : response;
                //        if ($.isFunction(callback)) {
                //            callback(result);
                //        }
                //        $($.ColorLife.loaderID).hide();
                //        $.ColorLife.hideLoading();
                //    },
                //    error: function (xhr, status) {
                //        alert(status);
                //    }
                //});
            },
            
            prevFolder: function () {
                this.loadFileFolder(this.getPrevFolder(this.currentFolder));
            },
            getPrevFolder: function (_currentFolder) {
                if (_currentFolder != this.rootFolder) {
                    return _currentFolder.substr(0, _currentFolder.lastIndexOf('/'));
                }
                else {
                    return this.rootFolder;
                }
            },         
            folderInfo: function (event) {
                // alert('Oaaa');
                var _callInfo = true;

                if (event) {
                    //alert($(event.target).parent().attr('class'));

                    if ($(event.target).hasClass(this.itemClass) || $(event.target).parent().hasClass(this.itemClass)) {

                        return;
                    }

                    $('.' + this.itemSelectedClass).addClass(this.itemSelectedNoFocusClass);

                }

                if ($.ColorLife.folderInfo.subFolders != undefined) {

                    var _icon = $.ColorLife.iconsPath + 'folder.gif';
                    var _html = '<div class="item-info item-info-icon" style="background: url(\'' + _icon + '\') no-repeat center center;">';
                    //_html += '<img class="" src="' + _icon + '" />';
                    _html += '</div>';
                    _html += '<div class="item-info item-info-content">';
                    _html += '<div class="line-1 item-info-name">' + $.ColorLife.String.format($.ColorLife.messages.folderInfo, $.ColorLife.folderInfo.subFolders, $.ColorLife.folderInfo.files) + '</div>';
                    _html += '</div>';

                    $($.ColorLife.itemInfoId).html(_html);
                }
            },
           

            refresh: function () {
                $.ColorLife.loadTreeFunction();
                $.ColorLife.loadFileFolder($.ColorLife.currentFolder);
            },
           
            zip: function () {
                $.Zebra_Dialog('Comming soon!', {
                    'type': 'information',
                    'title': 'Nén / giải nén File'
                });
            },
            openCommand: function () {
                var fileName = $(this.txtPath).val();                
                if ($.ColorLife.checkExt(fileName) === '') {
                    $.ColorLife.loadFileFolder(fileName);
                }
                else {
                    $("#myModalImage").modal('show');
                }
            },
            clipboardItems: function (_type) {
                this.clipboardType = _type;
                var _items = this.getSelectedItems();
                if (_items.length > 0) {
                    $('.' + this.itemClass).removeClass(this.itemCutClass); // clear cut item
                    this.clipboardData = _items.join('|');
                };
                if (_type == 'cut') {
                    $('.' + this.itemSelectedClass).addClass(this.itemCutClass);
                }

                $.Zebra_Dialog('Dữ liệu đã được lưu vào bộ nhớ tạm', {
                    'title': 'Copy',
                    'type': 'copy',
                    'buttons': false,
                    'modal': true,
                    'position': ['right - 20', 'top + 20'],
                    'auto_close': 2000

                });
            },
            past: function () {
                if (this.clipboardType == 'cut') {
                    var _params = '{"_filesOrFolders":"' + this.clipboardData + '","_destination":"' + this.currentFolder + '","_overwrite":' + true + '}';
                    $.ColorLife.ajaxCallback('Move', _params, $.ColorLife.refresh);
                }
                else {
                    var _params = '{"_filesOrFolders":"' + this.clipboardData + '","_destination":"' + this.currentFolder + '","_overwrite":' + true + '}';
                    $.ColorLife.ajaxCallback('Copy', _params, $.ColorLife.refresh);
                };
                this.clipboardData = '';
            },
            pasteItems: function () {
                if (this.String.isNullOrEmpty(this.clipboardData)) return;
                // var _overwrite = confirm(this.messages.overwriteExists);

                $.Zebra_Dialog(this.messages.overwriteExists, {
                    'type': 'question',
                    'title': 'Copy file / thư mục',
                    'buttons': [
                    { caption: 'Yes', callback: function () {
                        $.ColorLife.past();
                    }
                    },

                    { caption: 'No', callback: function () { } }
                ]
                });
            },
            copyCommand: function () {
                var fileName = $(this.txtPath).val();
                $.Zebra_Dialog('Dữ liệu đã được lưu vào bộ nhớ tạm', {
                    'title': 'Copy',
                    'type': 'copy',
                    'buttons': false,
                    'modal': true,
                    'position': ['right - 20', 'top + 20'],
                    'auto_close': 1000
                });
            },
            createNewFolder: function (name) {                
                if (name.length > 0) {
                    var params = "{'path':'" + $.ColorLife.currentFolder + "','name':'" + name + "'}";
                    $.ColorLife.ajaxCallback('CreateNewFolder', params, $.ColorLife.refresh);
                    return true;
                }
                else {
                   // alert("Bạn cần nhập tên thư mục");
                    return false;
                }
            },

            uploadCommand: function () {
                $('#myModalUpload').modal('show');

                $.ColorLife.doUpload();
            },

            deleteCommand: function () {
                $('#myModalDelete').modal('show');
            },
            deleteSelectedItem: function () {
                var fileName = $(this.txtPath).val();              
                if (fileName.length > 0) {
                    $.ColorLife.ajaxCallback('DeleteFileFolder', '{"path":"' + fileName + '"}', $.ColorLife.refresh);
                }
                else {
                    alert($.ColorLife.messages.mustSelectItem);
                }               
            },

            clickToReName: function () {
                $("." + $.ColorLife.itemNameClass).editable({
                    editBy: 'dblclick',
                    editClass: 'width80',
                    onSubmit: function (content) {
                        if (content.current != content.previous) {
                            var _oldName = $.ColorLife.currentFolder + '/' + content.previous;
                            var _newName = $.ColorLife.currentFolder + '/' + content.current;
                            var _params = '{"oldName":"' + _oldName + '","newName":"' + _newName + '"}';
                            $.ColorLife.ajaxCallback('RenameFileFolder', _params, $.ColorLife.refresh);
                            //FileManager.FileHelperServices.RenameFileFolder(_oldName, _newName, $.xFM.refresh);
                        }
                        //alert(content.current + ':' + content.previous)
                    }
                });
            },
            dragToSelect: function () {
                               // Init Select
                if ($.fn.selectable) {
                    $($.ColorLife.containerId).selectable({
                        selected: function (e, ui) {
                            $('li.ui-selected').addClass($.xFM.itemSelectedClass);
                        },
                        unselected: function (e, ui) {
                            $('li.ui-selected').removeClass($.xFM.itemSelectedClass);
                        }
                    });
                }
                                // Init Drag
                if ($.fn.draggable && $.fn.droppable) {


                    $("." + $.ColorLife.itemClass).draggable({
                        revert: true,
                        containment: $.ColorLife.containerId,
                        opacity: 0.5,
                        // helper: 'clone',
                        zIndex: 9999,
                        scroll: true,
                        scrollSpeed: 100
                    });

                    $("." + $.ColorLife.itemClass).droppable({

                        accept: '.xfm-item',
                        hoverClass: 'xfm-item-highlight',
                        drop: function (event, ui) {


                            var _target = $('#' + event.target.id);
                            if (_target.attr('type') == 'folder') {

                                $(this).addClass('xfm-item-highlight');

                                var _dest = _target.attr('rel');

                                var _items = $.ColorLife.getSelectedItems();

                                if (_items.length > 0) {

                                    var _overwrite = confirm($.ColorLife.messages.overwriteExists);

                                    var _params = '{"_filesOrFolders":"' + _items.join('|') + '","_destination":"' + _dest + '","_overwrite":' + _overwrite + '}';

                                    //$("." + $.xFM.itemClass).draggable('destroy');
                                    //$(ui.draggable).remove();

                                    $('.' + $.ColorLife.itemSelectedClass).remove();

                                    _target.removeClass('xfm-item-highlight');


                                    $.ColorLife.ajaxCallback('Move', _params);
                                }

                            }

                        }


                    });

                }

                                /*

                var selected = $([]), offset = { top: 0, left: 0 };
                //$("#xfmContainer").selectable();

                $(".xfm-item").draggable({

                start: function (ev, ui) {

                selected = $(".ui-selected").each(function () {
                var el = $(this);
                el.data("offset", el.position({ of: $.xFM.containerId })); //el.offset());

                });

                offset = $(this).position({ of: $.xFM.containerId }); //$(this).offset();

                },

                drag: function (ev, ui) {

                var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;

                selected.not(this).each(function () {
                var el = $(this), off = el.data("offset");
                el.css({ top: off.top + dt, left: off.left + dl });
                });

                }

                });

                */

            },

            loadTreeFunction: function () {
                $('#MainTree').jstree({
                    "json_data": {
                        "ajax": {
                            "url": this.serviceUrl+ "GetTreeData",
                            "type": "POST",
                            "data": "{path:'" + $.ColorLife.rootFolder + "'}",
                            "dataType": "json",
                            "contentType": "application/json charset=utf-8"
                        }
                    },
                    "themes": {
                        "theme": "default",
                        "dots": true,
                        "icons": true
                        // "url": "/content/filemanager/js/themes/apple/style.css"
                    },

                    "plugins": ["themes", "json_data", "dnd", "contextmenu", "ui", "crrm"]

                }).bind("select_node.jstree", function (e, data) {
                    var path = data.rslt.obj.attr('id');
                    // alert(path);
                    $.ColorLife.loadFileFolder(path);
                    // alert(a.data);
                }).bind("create.jstree", function (e, data) {
                    // alert(data.rslt.parent.attr("id"));
                    //$.post(
                    //        $.ColorLife.serviceUrl + "CreateNewFolder",
                    //        {
                    //            "path": data.rslt.parent.attr("id"),
                    //            "name": data.rslt.name
                    //        },
                    //        function (r) {
                    //            $.ColorLife.refresh();
                    //        }
                    //    );
                    var params = "{'path':'" + data.rslt.parent.attr("id") + "','name':'" + data.rslt.name + "'}";
                    $.ColorLife.ajaxCallback('CreateNewFolder', params, $.ColorLife.refresh);

                }).bind("delete_node.jstree", function (e, data) {
                    //$.post(
                    //        $.ColorLife.serviceUrl + "DeleteFileFolder",
                    //        {
                    //            "path": data.rslt.obj.attr("id")
                    //        },
                    //        function (r) {
                    //            $.ColorLife.refresh();
                    //        }
                    //    );
                    var params = "{'path':'" + data.rslt.obj.attr("id") + "'}";
                    $.ColorLife.ajaxCallback('DeleteFileFolder', params, $.ColorLife.refresh);
                }).bind("rename_node.jstree1", function (e, data) {

                    var parent = data.rslt.obj.attr("id");
                    var x = parent.substr(0, parent.lastIndexOf('/'));
                    $.post(
                               $.ColorLife.serviceUrl + "RenameFileFolder",
                               {
                                   "oldName": data.rslt.obj.attr("id"),
                                   "newName": x + '/' + data.rslt.name,
                               },
                               function (r) {                                   
                                   $.ColorLife.refresh();
                               }
                           );

                }).bind("move_node.jstree", function (e, data) {
                    data.rslt.o.each(function (i) {
                        $.ajax({
                            async: false,
                            type: 'POST',
                            url: "/FileManager/MoveData",
                            data: {
                                "source": $(this).attr("id"),
                                "target": data.rslt.np.attr("id")
                            },
                            success: function (response) {
                                // alert(response + " | " + $(i).attr("id") + " | " + data.rslt.np.attr("id"));
                                $.ColorLife.refresh();
                            }, error: function (xhr, status) {
                                alert(status);
                            }
                        });
                    });
                });
            },
            help: function () {
                alert('ok');

            },
            // Page Load
            onPageLoad: function () {
                
                $.ColorLife.loadTreeFunction();
                $.ColorLife.loadFileFolder($.ColorLife.rootFolder);
                
                $.ColorLife.returnOpenerId = $.ColorLife.getQueryString('returnId');
                $.ColorLife.tinymce = $.ColorLife.getQueryString('tinymce');
                
                ///////////
                // Keyboard Shortcut
                $(document).bind('keydown', 'h', function (evt) { $.ColorLife.help(); return false; });
                $(document).bind('keydown', 'f5', function (evt) { $.ColorLife.refresh(); return false; });
                $(document).bind('keydown', 'backspace', function (evt) { $.ColorLife.prevFolder(); return false; });
                $(document).bind('keydown', 'del', function (evt) { $.ColorLife.deleteCommand(); return false; });
                $(document).bind('keydown', 'shift+del', function (evt) { $.ColorLife.deleteSelectedItem(); return false; });
                         $(document).bind('keydown', 'ctrl+a', function (evt) { $.ColorLife.selectAllItems(); return false; });
                $(document).bind('keydown', 'ctrl+x', function (evt) { $.ColorLife.clipboardItems('cut'); return false; });
                $(document).bind('keydown', 'ctrl+c', function (evt) { $.ColorLife.clipboardItems('copy'); return false; });
                $(document).bind('keydown', 'ctrl+v', function (evt) { $.ColorLife.pasteItems(); return false; });
                $(document).bind('keydown', 'ctrl+u', function (evt) { $.ColorLife.uploadCommand(); return false; });


                // $(document).bind('click', function (evt) { $.ColorLife.folderInfo(evt); return false; });
                // $(document).bind('mousedown', function (evt) { $.ColorLife.folderInfo(evt); return false; });

                //$($.xFM.containerId).bind('mousedown', function (evt) { $.xFM.folderInfo(evt); return false; });

                $(document).bind('keydown', 'esc', function (evt) { $.ColorLife.hideLoading(); });
                /////////
            }
            ,
            demoFunction: function () {
                // alert('Huhu');
            }
            // Code tiep o day
        }
        // end ColorLife
    });   // end extend
})(jQuery);

